package com.example.controller;

import com.example.common.RequirePermission;
import com.example.common.Result;
import com.example.dto.AvatarUploadDTO;
import com.example.service.AvatarService;
import com.example.util.UserContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 头像管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/avatar")
@CrossOrigin
public class AvatarController {
    
    @Autowired
    private AvatarService avatarService;
    
    @Autowired
    private UserContextUtil userContextUtil;
    
    /**
     * 上传用户头像
     */
    @PostMapping("/upload")
    @RequirePermission("user:avatar:upload")
    public Result<AvatarUploadDTO> uploadAvatar(@RequestParam("file") MultipartFile file) {
        AvatarUploadDTO result = avatarService.uploadAvatar(file);
        return Result.success(result);
    }
    
    /**
     * 更新当前用户头像
     */
    @PutMapping("/update")
    @RequirePermission("user:avatar:update")
    public Result<Void> updateCurrentUserAvatar(@RequestBody String avatarUrl) {
        Long currentUserId = userContextUtil.getCurrentUserId();
        if (currentUserId == null) {
            return Result.error("用户未登录");
        }
        
        // 去掉JSON引号
        if (avatarUrl != null && avatarUrl.startsWith("\"") && avatarUrl.endsWith("\"")) {
            avatarUrl = avatarUrl.substring(1, avatarUrl.length() - 1);
        }
        
        avatarService.updateUserAvatar(currentUserId, avatarUrl);
        return Result.success();
    }
    
    /**
     * 上传并更新当前用户头像（一步完成）
     */
    @PostMapping("/upload-and-update")
    @RequirePermission("user:avatar:update")
    public Result<AvatarUploadDTO> uploadAndUpdateAvatar(@RequestParam("file") MultipartFile file) {
        log.info("开始处理头像上传并更新请求，文件名: {}", file.getOriginalFilename());

        Long currentUserId = userContextUtil.getCurrentUserId();
        log.info("当前用户ID: {}", currentUserId);

        if (currentUserId == null) {
            log.warn("用户未登录，无法上传头像");
            return Result.error("用户未登录");
        }

        try {
            // 上传头像
            log.info("开始上传头像文件到MinIO");
            AvatarUploadDTO uploadResult = avatarService.uploadAvatar(file);
            log.info("头像文件上传成功，URL: {}", uploadResult.getAvatarUrl());

            // 更新用户头像
            log.info("开始更新用户头像到数据库，userId: {}, avatarUrl: {}", currentUserId, uploadResult.getAvatarUrl());
            avatarService.updateUserAvatar(currentUserId, uploadResult.getAvatarUrl());
            log.info("用户头像更新完成");

            return Result.success(uploadResult);
        } catch (Exception e) {
            log.error("头像上传并更新失败", e);
            return Result.error("头像上传失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除当前用户头像
     */
    @DeleteMapping("/delete")
    @RequirePermission("user:avatar:delete")
    public Result<Void> deleteCurrentUserAvatar() {
        Long currentUserId = userContextUtil.getCurrentUserId();
        if (currentUserId == null) {
            return Result.error("用户未登录");
        }
        
        avatarService.deleteUserAvatar(currentUserId);
        return Result.success();
    }
    
    /**
     * 管理员更新指定用户头像
     */
    @PutMapping("/admin/update/{userId}")
    @RequirePermission("admin:avatar:update")
    public Result<Void> updateUserAvatar(@PathVariable Long userId, @RequestBody String avatarUrl) {
        // 去掉JSON引号
        if (avatarUrl != null && avatarUrl.startsWith("\"") && avatarUrl.endsWith("\"")) {
            avatarUrl = avatarUrl.substring(1, avatarUrl.length() - 1);
        }
        
        avatarService.updateUserAvatar(userId, avatarUrl);
        return Result.success();
    }
    
    /**
     * 管理员删除指定用户头像
     */
    @DeleteMapping("/admin/delete/{userId}")
    @RequirePermission("admin:avatar:delete")
    public Result<Void> deleteUserAvatar(@PathVariable Long userId) {
        avatarService.deleteUserAvatar(userId);
        return Result.success();
    }
} 